package common.action;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpServletRequest rq = (HttpServletRequest) request;
		HttpServletResponse rp = (HttpServletResponse) response;
		String path = rq.getServletPath();
		if(path.equals("/panel/")||path.equals("/panel")){
			HttpSession session = rq.getSession();
			String userName = (String) session.getAttribute("loginName");
			StringBuffer contextUrl = rq.getRequestURL();
			StringBuffer basePath  =  contextUrl.delete(
					contextUrl.length() - rq.getRequestURI().length(),
					contextUrl.length()).append(rq.getContextPath())
					.append("/");
			if (null == userName) {
			rp.sendRedirect(basePath + "panel/login.jsp");
			}else{
			rp.sendRedirect(basePath + "panel/index.jsp");
			}
		}
		else if (path.equals("/panel/login.jsp")
				|| path.equals("/login.action")
				||path.startsWith("/panel/success.jsp")
				||path.startsWith("/ueditorupload")
				||path.startsWith("/uploadAction")) {//后面两个由于swf上传session丢失
			filterChain.doFilter(request, response);
		} 
		else
		{
			HttpSession session = rq.getSession();
			String userName = (String) session.getAttribute("loginName");
			// 验证用户登录
			if (null == userName) {
				StringBuffer contextUrl = rq.getRequestURL();
				StringBuffer basePath = contextUrl.delete(
						contextUrl.length() - rq.getRequestURI().length(),
						contextUrl.length()).append(rq.getContextPath())
						.append("/");
				rp.sendRedirect(basePath + "panel/login.jsp");
			} else {
				filterChain.doFilter(request, response);
			}
		}
		
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
